package com.liangzai.service.impl;

import com.liangzai.entity.GatewayHandlerEntity;
import com.liangzai.handler.GatewayHandler;
import com.liangzai.mapper.GatewayHandlerMapper;
import com.liangzai.utils.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GatewayHandlerService {
    @Autowired
    private GatewayHandlerMapper gatewayHandlerMapper;
    private GatewayHandler firstGatewayHandler;

    public GatewayHandler getDbGatewayHandler() {
        if (firstGatewayHandler != null) {
            return firstGatewayHandler;
        }
        // 1.获取第一个GatewayHandler信息
        GatewayHandlerEntity firstGatewayHandlerEntity = gatewayHandlerMapper.getFirstGatewayHandler();
        if (firstGatewayHandlerEntity == null) {
            return null;
        }
        // 2.获取第一个firstGatewayHandler spring容器中的id
        String handlerBeanId = firstGatewayHandlerEntity.getHandlerId();
        // 3.从spring容器中获取对应的对象 firstGatewayHandler
        GatewayHandler firstGatewayHandler = SpringUtils.getBean(handlerBeanId, GatewayHandler.class);
        // 4.使用white循环 设置下一个节点 同时定义循环遍历临时对象
        GatewayHandler tempGatewayHandler = firstGatewayHandler;
        // 5.获取下一个节点
        String nextHandlerBeanId = firstGatewayHandlerEntity.getNextHandlerId();
        while (!StringUtils.isEmpty(nextHandlerBeanId)) {
            GatewayHandlerEntity nextGatewayHandlerEntity = gatewayHandlerMapper.getByHandler(nextHandlerBeanId);
            if (nextGatewayHandlerEntity == null) {
                break;
            }
            // 6.从springboot容器获取下一个handler 对象
            String tempNextHandlerBeanId = nextGatewayHandlerEntity.getHandlerId();
            GatewayHandler nextGatewayHandler = SpringUtils.getBean(tempNextHandlerBeanId, GatewayHandler.class);
            // 7.设置当前handler下一个handler对象
            tempGatewayHandler.setHandler(nextGatewayHandler);
            tempGatewayHandler = nextGatewayHandler;
            // 8.循环遍历下一个节点
            nextHandlerBeanId = nextGatewayHandlerEntity.getNextHandlerId();
        }
        this.firstGatewayHandler = firstGatewayHandler;
        return firstGatewayHandler;
    }
}
